const { exec } = require('../database/mysql')

const xss = require('xss')

let getList = (author, keyword) => {
    let sql = `
    select id,title,content,createtime,author
    from blogs
    where 1 = 1
    `
    // 1 = 1 可以保证sql语句可执行
    if (author) sql += `and author = '${author}' `
    if (keyword) sql += `and title like '%${keyword}%' `
    sql += `order by createtime asc`
    return exec(sql)
}

let getDetail = async id => {
    let sql = `
    select id,title,content,createtime,author
    from blogs
    where id=${id};
    `
    let rows = await exec(sql)
    return rows[0]
}

// blogData是一个文章对象，包含title、content
let postNew = async (blogData = {}) => {
    let { title, content, author } = blogData
    title = xss(title)
    content = xss(content)
    author = xss(author)
    let createTime = Date.now()
    let sql = `
    insert into blogs (title,content,createTime,author)
    values ('${title}','${content}',${createTime},'${author}');
    `
    let insertData = await exec(sql)
    return {
        id: insertData.insertId,
        title,
        content,
        createTime,
        author
    }
}

/**
 * id为更新的文章ID
 * blogData是一个文章对象，包含title、content
 */
let postUpdate = async (id, blogData = {}) => {
    let { title, content } = blogData
    title = xss(title)
    content = xss(content)
    let sql = `
    update blogs
    set title='${title}', content='${content}'
    where id = ${id};
    `
    let update = await exec(sql)
    return {
        id,
        state: update.affectedRows ? true : false
    }
}

// id 要删除的文章ID
let postDelete = async (id, author) => {
    author = xss(author)
    let sql = `
    delete from blogs
    where id='${id}'
    and author = '${author}'
    `
    let delData = await exec(sql)
    return delData.affectedRows ? true : false
}

module.exports = {
    getList,
    getDetail,
    postNew,
    postUpdate,
    postDelete
}
